package com.ikkong.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.alibaba.druid.support.json.JSONUtils;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.toolbox.Record;
import com.ikkong.platform.model.BaiduAccount;
import com.jfinal.kit.HttpKit;
import com.qiniu.util.StringUtils;

public class OCRUtil {

	/**
	 * 获取API访问token 该token有一定的有效期，需要自行管理，当失效时需重新获取.
	 * 
	 * @param ak
	 *            - 百度云官网获取的 API Key
	 * @param sk
	 *            - 百度云官网获取的 Securet Key
	 * @return assess_token 示例：
	 *         "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
	 */
	public static String getBaiduAccessToken() {
		try {
			Blade baiduAccountBlade = Blade.create(BaiduAccount.class);
			BaiduAccount baiduAccount = baiduAccountBlade.findFirstBy(
					"id=#{id}",
					 Record.create().set("id", 1));
			String token = "", apiKey = "", secretKey = "";
			if (baiduAccount != null) {
				token = baiduAccount.getAccessToken();
				apiKey=baiduAccount.getApiKey();
				secretKey=baiduAccount.getSecretKey();
			}
			if (!StringUtils.isNullOrEmpty(token)) {
				// 判断有效时间 Access Token的有效期(秒为单位，一般为1个月)；
				java.util.Date end = new java.util.Date();
				java.util.Date start = new java.util.Date(baiduAccount
						.getAccessTokenTime().getTime());
				if ((end.getTime() - start.getTime()) / 1000 >= 30 * 24 * 60 * 60) {
					// 获取token地址
					String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
					// 1. grant_type为固定参数
					// 2. 官网获取的 API Key
					// 3. 官网获取的 Secret Key
					String getAccessTokenUrl = authHost+"grant_type=client_credentials&client_id="+apiKey+"&client_secret="+secretKey;
					String ret=HttpKit.get( getAccessTokenUrl);
					JSONObject jsonObject = new JSONObject(ret);
					String access_token = jsonObject.getString("access_token");
					if (!StringUtils.isNullOrEmpty(access_token)) {
						try {
							// 重置token
							baiduAccount.setAccessToken(access_token);
							// 重置事件
							baiduAccount.setAccessTokenTime(new Date());
							baiduAccountBlade.update(baiduAccount);
							token=access_token;
						} catch (Exception e) {
							token = null;
							// 获取token失败
							System.out.println(e.getMessage());
						}
					}
					return token;
				} else {
					return baiduAccount.getAccessToken();
				}
			} else {
				// 获取token地址
				String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
				// 1. grant_type为固定参数
				// 2. 官网获取的 API Key
				// 3. 官网获取的 Secret Key
				String getAccessTokenUrl = authHost+"grant_type=client_credentials&client_id="+apiKey+"&client_secret="+secretKey;
				getAccessTokenUrl=getAccessTokenUrl.replaceAll("\t|\r|\n", "");
				Map<String, String> param = new HashMap<String, String>();
				param.put("grant_type", "client_credentials");
				param.put("client_id", apiKey);
				param.put("client_secret", secretKey);
				Map<String,String> headers=new HashMap<String,String>();
				headers.put("Content-Type","application/json");
				String ret=HttpKit.get(getAccessTokenUrl);
				
				JSONObject jsonObject = new JSONObject(ret);
				String access_token = jsonObject.getString("access_token");
				if (!StringUtils.isNullOrEmpty(access_token)) {
					try {
						// 重置token
						baiduAccount.setAccessToken(access_token);
						// 重置事件
						baiduAccount.setAccessTokenTime(new Date());
						baiduAccountBlade.update(baiduAccount);
						token=access_token;
					} catch (Exception e) {
						token = null;
						// 获取token失败
						System.out.println(e.getMessage());
					}
				}
				return token;
			}
		} catch (Exception e) {
			System.err.printf("获取token失败！");
			e.printStackTrace(System.err);
		}
		return null;
	}

}